package by.gravity.billprinter.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.util.Log;

public class FileUtils {

	public static String readAssets(String fileName, Context context) {
		StringBuilder returnString = new StringBuilder();
		InputStream fIn = null;
		InputStreamReader isr = null;
		BufferedReader input = null;
		try {
			fIn = context.getResources().getAssets().open(fileName);
			isr = new InputStreamReader(fIn, "UTF-8");
			input = new BufferedReader(isr);
			String line = "";
			while ((line = input.readLine()) != null) {
				returnString.append(line);
			}
		} catch (Exception e) {
			e.getMessage();
		} finally {
			try {
				if (isr != null)
					isr.close();
				if (fIn != null)
					fIn.close();
				if (input != null)
					input.close();
			} catch (Exception e2) {
				e2.getMessage();
			}
		}
		return returnString.toString();
	}

	public static void writeToFile(String path, String fileName, String str) {

		if (str == null) {
			Log.e(FileUtils.class.getSimpleName(), "won't write null string to file");
			return;
		}

		File file = new File(path, fileName);
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file, true);
			fileWriter.write(str);
			fileWriter.write("\n");
			fileWriter.flush();
			Log.i(FileUtils.class.getSimpleName(), "written to file: " + file.getName());
		} catch (IOException e) {
			Log.e(FileUtils.class.getSimpleName(), "error writing xml to file", e);
		} finally {
			if (fileWriter != null) {
				try {
					fileWriter.close();
				} catch (IOException e) {
				}
			}
		}
	}
}
